package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.Subject;
import model.SubjectMsg;
import service.SubjectService;
import service.UserService;
import service.impl.SubjectServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: wyt
 * @date: 2022/12/19 16:12
 */
@WebServlet("/subjectListName")
public class SubjectListByNameServlet extends HttpServlet {
    SubjectService subjectService = new SubjectServiceImpl();
    UserService userService=new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //Json转换
        BufferedReader bufferedReader = new BufferedReader(request.getReader());
        String line = null;
        final StringBuilder json = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());

        //接收数据
        int pageSize=8;
        String partName = jsonObject.getString("partName");
        int pageIndex = Integer.parseInt(jsonObject.getString("pageIndex"));
        List<Subject> subjects=subjectService.findByName(partName,pageIndex,pageSize);

        int count=subjectService.countByName(partName);
        //创建容器
        List<SubjectMsg> subjectMsgList =new ArrayList<>();

        for(Subject subject:subjects){
            SubjectMsg subjectMsg=new SubjectMsg();
            subjectMsg.setSubject(subjectService.get(subject.getSid()));
            subjectMsg.setUser(userService.findById(subject.getUid()));
            subjectMsgList.add(subjectMsg);
        }

        System.out.println("ssubmsg:"+subjectMsgList);
        //发送数据给前端
        JSONObject message = new JSONObject();
        message.put("subjectMsg",subjectMsgList);
        message.put("pageCount",count % pageSize != 0 ? count / pageSize + 1 : count / pageSize);
        response.getWriter().write(message.toString());
    }
}